import json
import base64
import os
import requests
from flask import Flask, request, jsonify, render_template

app = Flask(__name__)

# 百度智能云 图像识别 API 配置
BAIDU_API_URL = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant"
ACCESS_TOKEN = "24.1d1dbe0ff0d67fd32dd25af9f82dc0ca.2592000.1735562768.282335-116433268"  # 替换为你自己的 Access Token

# 百度智能云 AI 对话 API 配置
API_KEY = "57QRsp5IqyeEaBPJjnhZPTvo"
SECRET_KEY = "JokwkowoPa6N0Iifcxxg3rmebOuav5so"

# 图片上传目录
UPLOAD_FOLDER = "static/images"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

# 获取 Access Token
def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    response = requests.post(url, params=params)
    if response.status_code == 200:
        return response.json().get("access_token")
    else:
        return None

# 请求智能对话 API
def get_ai_response(user_input):
    access_token = get_access_token()
    if not access_token:
        return "获取 Access Token 失败"

    url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/yi_34b_chat?access_token={access_token}"
    payload = json.dumps({
        "messages": [{"role": "user", "content": user_input}]
    })
    headers = {'Content-Type': 'application/json'}
    response = requests.post(url, headers=headers, data=payload)

    try:
        response_data = response.json()
        return response_data.get("result", "抱歉，我没有得到有效的回答。")
    except json.JSONDecodeError:
        return "返回的响应不是有效的 JSON 格式。"

# 处理图片上传并识别植物
@app.route('/upload', methods=['POST'])
def upload_image():
    image = request.files['image']  # 获取上传的文件
    file_path = os.path.join(UPLOAD_FOLDER, image.filename)
    image.save(file_path)  # 保存图片

    # 将图片转为 Base64 编码
    with open(file_path, "rb") as f:
        img_base64 = base64.b64encode(f.read()).decode()

    # 请求百度智能云 API 识别图片
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    data = {"image": img_base64, "access_token": ACCESS_TOKEN}
    response = requests.post(BAIDU_API_URL, headers=headers, data=data)
    result = response.json()  # 获取识别结果

    # 识别植物的名称
    if "result" in result:
        plant_name = result["result"][0]["name"]
    else:
        plant_name = "未知植物"

    return jsonify({"plant_name": plant_name})

# 处理 AI 对话请求
@app.route('/ask', methods=['POST'])
def ask_question():
    question = request.json.get('question')
    if not question:
        return jsonify({"error": "No question provided"}), 400

    answer = get_ai_response(question)
    return jsonify({"answer": answer})

# 首页
@app.route('/')
def index():
    return render_template('植物识别.html')
UPLOAD_FOLDER = "static/images"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
if __name__ == '__main__':
    app.run(debug=True)
